package controllers

import (
	"c111/cache"
	"c111/models"
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
)

type ShopController struct {
	beego.Controller
}
type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	age, _ := c.GetInt("age")
	shop := models.Shop{
		Name: name,
		Age:  age,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = Msg{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Msg{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	var shop []models.Shop
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	offset := (page - 1) * size
	err := models.DB.Find(&shop).Limit(size).Offset(offset).Error
	if err != nil {
		c.Data["json"] = Msg{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()

		return
	}

	key := "shop_list"
	res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if res != "" {
		fmt.Println("从缓存中查询")
		json.Unmarshal([]byte(res), &shop)
	} else {
		fmt.Println("从数据库中查询")
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*24)
	}

	c.Data["json"] = Msg{
		Code: 200,
		Msg:  "查询成功",
		Data: shop,
	}
	c.ServeJSON()
	return
}
func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Shop{}, id).Error
	if err != nil {
		c.Data["json"] = Msg{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Msg{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Detail() {
	id, _ := c.GetInt("id")
	var shop models.Shop
	key := "shop_detail" + strconv.Itoa(id)
	res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if res != "" {
		fmt.Println("从缓存中查询")
		json.Unmarshal([]byte(res), &shop)
	} else {
		fmt.Println("从数据库中查询")
		models.DB.Where("id=?", id).First(&shop)
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, key, jsonData, 0)
	}
	c.Data["json"] = Msg{
		Code: 200,
		Msg:  "详情查看成功",
		Data: shop,
	}
	c.ServeJSON()
	return
}
